package websocketServer;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * WebSocket服务
 */
@ServerEndpoint("/ws/{sid}")
public class WebSocketServer {

    private static Map<String, Session> sessionMap = new HashMap<>();
    private static List<String> messages = new ArrayList<>();
    private static Set<String> connectedClients = new HashSet<>();
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "建立连接");
//        sendToAllClient(sid+"进入了匿名聊天室！");
        sessionMap.put(sid, session);
        // 判断是否是新的连接
        if (!connectedClients.contains(sid)) {
            for (String message : messages) {
//                sendToClient(sid, message);
            }
            // 标记为已连接
            connectedClients.add(sid);
        }
    }

    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        LocalDateTime now = LocalDateTime.now();
        String formattedTime = now.format(formatter);
//        String messageToSend = formattedTime + "---来自" + sid + "的消息:" + "<span id=\"message\" style=\"color:red;font-size:25px;\">" + message + "</span>";
        sendToAllClient(sid + "-" + message);
        System.out.println("收到来自客户端：" + sid + "的信息:" + message);
        setMessages(message);
    }

    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
        connectedClients.remove(sid); // 连接断开时移除对应的标记
    }

    public void sendToAllClient(String message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendToClient(String sid, String message) {
        Session session = sessionMap.get(sid);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void setMessages(String message) {
        messages.add(message);
    }
}
